import { asyncRoutes, staticRoutes } from '@/router'
import { filterAsyncRoutes } from '@/utils/permission'

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = staticRoutes.concat(routes)
  }
}

const actions = {
  /**
   * 根据用户角色生成动态路由
   * @param {*} context 上下文
   * @param {*} role 当前用户角色
   * @returns 生成的动态路由
   */
  generateRoutes({ commit }, role) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, role)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
